import {handlerContainer} from "../containers/handlerContainer"
import {LogFactory} from "../support/log"
import {Handler} from "../web/Handler"
import {createStandardHttpPath, parseRequestMappingPattern, requestPatternMatch} from "../support/util/path"
import HandlerExecutionChain from "../web/HandlerExecutionChain"
import {HttpMethod} from "../support/enum/HttpMethod"

class HandlerManager{
  private logger = LogFactory.getLogger("HandlerManager")

  static handlerList = handlerContainer

  static resolveController = (Ctor: any) => {
    // 将Controller解析为url mapping handler
    const context: string = Ctor.context
    Object.keys(Ctor).forEach(key => {
      if(key === "context") return
      const mappingObj = Ctor[key] as MappingObject
      const handler = new Handler()
      handler.handlerExecutor = Ctor.prototype[key]
      handler.pathRaw = createStandardHttpPath(context, mappingObj.path)
      handler.pattern = parseRequestMappingPattern(handler.pathRaw)
      handler.method = mappingObj.method
      const handlerExecutionChain = new HandlerExecutionChain(handler)
      HandlerManager.handlerList.push(handlerExecutionChain)
    })
  }


  match(req: HttpRequest) {
    let handler: HandlerExecutionChain = null
    HandlerManager.handlerList.some(item => {
      const handlerMethod = item.handler.method
      if (handlerMethod !== HttpMethod.ALL && handlerMethod !== req.method) {
        return null
      }
      const [match, params] = requestPatternMatch(req.url, item.handler.pattern)
      if (match) {
        handler = item
        Object.keys(params).forEach(key => {
          req.setParam(key, params[key])
        })
        return
      }
    })
    return handler
  }


}

export {HandlerManager}
